document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const sidebar = document.querySelector('.sidebar');
    const toggleBtn = document.getElementById('toggleSidebar');
    const menu = document.getElementById('menu');
    const content = document.getElementById('content');
    const backToTop = document.getElementById('backToTop');
    const themeToggleBtn = document.getElementById('themeToggleBtn');
    const loading = document.getElementById('loading');
    const friendLinkBtn = document.getElementById('friendLinkBtn');
    const friendLinkModal = document.getElementById('friendLinkModal');
    const sidebarOverlay = document.getElementById('sidebarOverlay');

    // 获取导航数据
    async function fetchNavigation() {
        try {
            loading.classList.add('active');
            const response = await fetch('http://127.0.0.1:8000/api/navigation');
            const data = await response.json();
            if (data.code === 200) {
                renderNavigation(data.data);
            }
        } catch (error) {
            console.error('Error fetching navigation:', error);
            content.innerHTML = '<div class="error">加载失败，请刷新页面重试</div>';
        } finally {
            loading.classList.remove('active');
        }
    }

    // 渲染导航菜单和内容
    function renderNavigation(data) {
        // 渲染菜单
        const menuHTML = data.map(category => `
            <div class="menu-category">
                <div class="menu-item" data-id="${category.id}">
                    <i class="${category.icon}"></i>
                    <span>${category.title}</span>
                    <i class="fas fa-chevron-down submenu-arrow"></i>
                </div>
                <div class="submenu">
                    ${category.children.map(subcat => `
                        <div class="submenu-item" data-id="${category.id}-${subcat.id}">
                            <span>${subcat.title}</span>
                        </div>
                    `).join('')}
                </div>
            </div>
        `).join('');
        menu.innerHTML = menuHTML;

        // 渲染内容
        const contentHTML = data.map(category => `
            <section class="category-section" id="category-${category.id}">
                <h2 class="category-title">
                    <i class="${category.icon}"></i>
                    ${category.title}
                </h2>
                ${category.children.map(subcat => `
                    <div class="subcategory" id="subcategory-${category.id}-${subcat.id}">
                        <h3 class="subcategory-title">
                            <span>${subcat.title}</span>
                        </h3>
                        <div class="links-grid">
                            ${subcat.websites.map(link => `
                                <a href="${link.url}" class="link-card" target="_blank">
                                    <div class="link-card-header">
                                        <i class="${link.icon}"></i>
                                        <h4>${link.title}</h4>
                                    </div>
                                    <p class="link-description">${link.description}</p>
                                </a>
                            `).join('')}
                        </div>
                    </div>
                `).join('')}
            </section>
        `).join('');
        content.innerHTML = contentHTML;
    }

    // 友链模态框相关事件
    if (friendLinkBtn && friendLinkModal) {
        friendLinkBtn.addEventListener('click', () => {
            friendLinkModal.style.display = 'block';
        });

        // 关闭模态框
        friendLinkModal.querySelector('.close-modal')?.addEventListener('click', () => {
            friendLinkModal.style.display = 'none';
        });

        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target === friendLinkModal) {
                friendLinkModal.style.display = 'none';
            }
        });

        // 提交友链申请
        friendLinkModal.querySelector('form')?.addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            try {
                const response = await fetch('http://127.0.0.1:8000/api/friend-link', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                if (result.code === 200) {
                    alert('申请提交成功！');
                    friendLinkModal.style.display = 'none';
                    e.target.reset();
                } else {
                    alert('提交失败：' + result.message);
                }
            } catch (error) {
                console.error('Error submitting friend link:', error);
                alert('提交失败，请稍后重试');
            }
        });
    }

    // 侧边栏切换按钮状态更新
    function updateToggleButton() {
        if (sidebar.classList.contains('collapsed') || !sidebar.classList.contains('expanded')) {
            toggleBtn.innerHTML = '<i class="fas fa-bars"></i>';
        } else {
            toggleBtn.innerHTML = '<i class="fas fa-times"></i>';
        }
    }

    // 关闭侧边栏
    function closeSidebar() {
        sidebar.classList.remove('expanded');
        sidebarOverlay.classList.remove('active');
        updateToggleButton();
    }

    // 侧边栏切换
    toggleBtn.addEventListener('click', () => {
        if (window.innerWidth <= 768) {
            sidebar.classList.toggle('expanded');
            sidebarOverlay.classList.toggle('active');
        } else {
            sidebar.classList.toggle('collapsed');
        }
        updateToggleButton();
    });

    // 点击遮罩层关闭侧边栏
    sidebarOverlay.addEventListener('click', closeSidebar);

    // 窗口大小改变时处理
    window.addEventListener('resize', () => {
        if (window.innerWidth > 768) {
            closeSidebar();
            sidebarOverlay.classList.remove('active');
        }
    });

    // 添加一个滚动到指定元素的辅助函数
    function scrollToElement(element) {
        const headerHeight = 64; // 顶部栏高度
        const elementPosition = element.getBoundingClientRect().top;
        const offsetPosition = elementPosition + window.pageYOffset - headerHeight;

        window.scrollTo({
            top: offsetPosition,
            behavior: 'smooth'
        });
    }

    // 修改菜单项点击事件中的滚动代码
    menu.addEventListener('click', (e) => {
        const menuItem = e.target.closest('.menu-item');
        const submenuItem = e.target.closest('.submenu-item');

        if (submenuItem && window.innerWidth <= 768) {
            closeSidebar();
        }

        if (menuItem) {
            e.stopPropagation();
            const menuCategory = menuItem.parentElement;
            const wasActive = menuCategory.classList.contains('active');
            
            // 关闭其他所有展开的菜单
            document.querySelectorAll('.menu-category').forEach(cat => {
                if (cat !== menuCategory) {
                    cat.classList.remove('active');
                }
            });
            document.querySelectorAll('.menu-item').forEach(item => {
                if (item !== menuItem) {
                    item.classList.remove('active');
                }
            });

            // 切换当前菜单的状态
            menuCategory.classList.toggle('active');
            menuItem.classList.toggle('active');

            const id = menuItem.dataset.id;
            const section = document.getElementById(`category-${id}`);
            if (section) {
                scrollToElement(section);
            }
        }

        if (submenuItem) {
            e.preventDefault();
            e.stopPropagation();
            
            // 移除所有子菜单项的活动状态
            document.querySelectorAll('.submenu-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // 确保父级菜单保持展开状态
            const menuCategory = submenuItem.closest('.menu-category');
            const menuItem = menuCategory.querySelector('.menu-item');
            
            // 关闭其他所有展开的菜单
            document.querySelectorAll('.menu-category').forEach(cat => {
                if (cat !== menuCategory) {
                    cat.classList.remove('active');
                }
            });
            document.querySelectorAll('.menu-item').forEach(item => {
                if (item !== menuItem) {
                    item.classList.remove('active');
                }
            });
            
            // 激活当前菜单和子菜单项
            menuCategory.classList.add('active');
            menuItem.classList.add('active');
            submenuItem.classList.add('active');
            
            const id = submenuItem.dataset.id;
            const section = document.getElementById(`subcategory-${id}`);
            if (section) {
                scrollToElement(section);
            }

            // 在移动设备上点击后收起侧边栏
            if (window.innerWidth <= 768) {
                closeSidebar();
            }
        }
    });

    // 添加滚动监听
    let ticking = false;
    document.addEventListener('scroll', () => {
        if (!ticking) {
            window.requestAnimationFrame(() => {
                updateActiveMenuItem();
                updateBackToTopButton();
                ticking = false;
            });
            ticking = true;
        }
    });

    // 修改滚动监听中的位置计算
    function updateActiveMenuItem() {
        const sections = document.querySelectorAll('.category-section');
        const subsections = document.querySelectorAll('.subcategory');
        
        // 获取视窗中心点，考虑顶部栏高度
        const headerHeight = 64;
        const viewportMiddle = (window.innerHeight - headerHeight) / 3 + headerHeight;
        
        // 检查主分类和子分类的可见性
        let activeCategory = null;
        let activeSubcategory = null;
        let minDistance = Infinity;
        
        // 检查主分类
        sections.forEach(section => {
            const rect = section.getBoundingClientRect();
            const distance = Math.abs(rect.top - viewportMiddle);
            
            if (distance < minDistance && rect.top <= viewportMiddle) {
                minDistance = distance;
                activeCategory = section.id.split('-')[1];
            }
        });

        // 重置最小距离用于子分类检查
        minDistance = Infinity;
        
        // 检查子分类
        if (activeCategory) {
            const currentCategorySubsections = document.querySelectorAll(`#category-${activeCategory} .subcategory`);
            currentCategorySubsections.forEach(subsection => {
                const rect = subsection.getBoundingClientRect();
                const distance = Math.abs(rect.top - viewportMiddle);
                
                if (distance < minDistance && rect.top <= viewportMiddle) {
                    minDistance = distance;
                    activeSubcategory = subsection.id.split('-')[2];
                }
            });

            // 更新菜单状态
            // 移除所有活动状态
            document.querySelectorAll('.menu-category').forEach(cat => {
                cat.classList.remove('active');
            });
            document.querySelectorAll('.menu-item').forEach(item => {
                item.classList.remove('active');
            });
            document.querySelectorAll('.submenu-item').forEach(item => {
                item.classList.remove('active');
            });

            // 找到对应的菜单项
            const menuCategory = document.querySelector(`.menu-item[data-id="${activeCategory}"]`).parentElement;
            const menuItem = menuCategory.querySelector('.menu-item');
            
            // 展开并激活主菜单
            menuCategory.classList.add('active');
            menuItem.classList.add('active');

            // 如果有活动的子分类，激活对应的子菜单项
            if (activeSubcategory) {
                const submenuItem = menuCategory.querySelector(`.submenu-item[data-id="${activeCategory}-${activeSubcategory}"]`);
                if (submenuItem) {
                    submenuItem.classList.add('active');
                }
            }
        }
    }

    // 更新回到顶部按钮
    function updateBackToTopButton() {
        if (window.pageYOffset > 300) {
            backToTop.classList.add('visible');
        } else {
            backToTop.classList.remove('visible');
        }
    }

    // 回到顶部
    backToTop.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });

    // 主题切换
    themeToggleBtn.addEventListener('click', () => {
        document.body.classList.toggle('dark-theme');
        document.body.classList.toggle('light-theme');
        
        // 保存主题偏好
        const isDark = document.body.classList.contains('dark-theme');
        localStorage.setItem('theme', isDark ? 'dark' : 'light');
    });

    // 加载保存的主题
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
        document.body.classList.remove('light-theme', 'dark-theme');
        document.body.classList.add(`${savedTheme}-theme`);
    }

    // 初始化
    fetchNavigation();
});
